package hackbard.piratradar;

import java.io.IOException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.ServiceConnection;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Piratradar extends ListActivity {
	public static final String PREFS_NAME = "PiratRadar";
	private LocationManager lm;
	private LocationListener locationListener;
	private Location location = null;
	// Intent intent = null;
	private java.util.List<String> liste = new ArrayList<String>();
	public static final int MENUE_REFRESH = Menu.FIRST;
	public static final int MENUE_CONFIG = Menu.FIRST + 1;
	public static final int MENUE_SERVICE = Menu.FIRST + 2;
	public static final int MENUE_VERSION = Menu.FIRST + 3;
	private MonitorService _boundService = null;
	private boolean _isBound = false;
	private Intent i;
	private Integer _UPDATE_ = 8;

	private ServiceConnection _connection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder binder) {
			_boundService = ((MonitorService.LocalBinder) binder).getService();
		}

		// @Override
		public void onServiceDisconnected(ComponentName name) {
			// / unexpectedly disconnected,we should never see this happen.
			_boundService = null;
		}
	};

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.overview);
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		/*
		 * TODO: check if service is running
		 */
		i = new Intent(this, MonitorService.class);
		if (settings.getBoolean("gpsautoupdater", true)) {
			Log.w("INFO", "gpsautoupdater Aktiv");
			startService(i);
		}

		refresh();
	}

	private void bindService() {
		Log.w("INFO","Bind Service");
		bindService(i, _connection, Context.BIND_AUTO_CREATE);
		_isBound = true;
	}

	private void unbindService() {
		if (_isBound) {
			unbindService(_connection);
			_isBound = false;
		}
	}

	private void startService() {
		Log.w("INFO","Starte Service");
		this.startService(i);
	}

	private void stopService() {
		Log.w("INFO","Stoppe Service");
		this.stopService(i);
		

	}

	public void refresh() {
		if (liste != null) {
			liste.clear();
		}
		try {
			lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locationListener = new MyLocationlistener();
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					locationListener);
		} catch (Exception e) {
			Toast.makeText(getBaseContext(),
					"GPS ist deaktiviert, oder du hast keinen empfang!",
					Toast.LENGTH_SHORT).show();
			Log.w("ERROR", "L: 69" + e.getMessage());
		}
		liste = getGpsData();
		if (liste != null) {
			ListAdapter anzeige = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, liste);
			setListAdapter(anzeige);
		} else {
			liste = new ArrayList<String>();
			liste.add("Keine Piraten im Umkreis");
		}
		Toast
				.makeText(getBaseContext(), "Abfrage beendet!",
						Toast.LENGTH_SHORT).show();
	}

	public void setMainMenu(Menu menu) {
		menu.setQwertyMode(true);
		@SuppressWarnings("unused")
		MenuItem item1 = menu.add(0, MENUE_REFRESH, 0, "Refresh").setCheckable(
				true);
		item1 = menu.add(0, MENUE_CONFIG, 0, "Configuration")
				.setCheckable(true);

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		/*
		 * TODO: check if service is running
		 */
		if (settings.getBoolean("gpsautoupdater", true)) {
			item1 = menu.add(0, MENUE_SERVICE, 0, "Beende Updater")
					.setCheckable(true);
		} else {
			item1 = menu.add(0, MENUE_SERVICE, 0, "Starte Updater")
					.setCheckable(true);
		}
		item1 = menu.add(0, MENUE_VERSION, 0, "Version").setCheckable(true);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		setMainMenu(menu);
		return super.onCreateOptionsMenu(menu);
	}

	public void getConfigLayout() {
		Intent intent = new Intent(Piratradar.this, Configuration.class);
		startActivity(intent);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENUE_REFRESH:
			refresh();
			return true;
		case MENUE_CONFIG:
			getConfigLayout();
			return true;
		case MENUE_VERSION:
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			Toast.makeText(getBaseContext(),
					"Deine Version: " + settings.getInt("update", 1),
					Toast.LENGTH_SHORT).show();
			return true;
		case MENUE_SERVICE:
			if (i != null) {
				stopService(i);
				i = null;
				item.setTitle("Starte Updater");
			} else {
				i = new Intent(this, MonitorService.class);
				startService(i);
				item.setTitle("Beende Updater");
			}
			return true;
		}
		return true;
	}

	private List<String> getGpsData() {
		try {
			lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			locationListener = new MyLocationlistener();
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
					locationListener);
			location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		} catch (Exception e) {
		}

		if (location != null) {
			return getGpsFromWeb();
		} else {
			TextView myLocationText = null;
			myLocationText = (TextView) findViewById(R.string.keineDaten);
			if (myLocationText != null) {
				myLocationText.setText("Bitte schalte dein GPS ein!");
			}

			return null;
		}
	}

	private List<String> getGpsFromWeb() {
		String url = "http://piratenradar.de/output.php";
		int idist;
		Map<String, String> kvPairs = new HashMap<String, String>();
		kvPairs.put("lon", String.valueOf(location.getLongitude()));
		kvPairs.put("lat", String.valueOf(location.getLatitude()));
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		kvPairs.put("nick", settings.getString("nick", "anonymus"));
		try {
			HttpResponse re = HTTPPoster.doPost(url, kvPairs);
			String site_s = EntityUtils.toString(re.getEntity());
			try {
				JSONArray jarray = new JSONArray(site_s);
				int anz = jarray.length();
				List<String> list = new ArrayList<String>();
				for (int i = 0; i < anz; i++) {
					String dist = jarray.getJSONObject(i).getString("dist");
					String nick = jarray.getJSONObject(i).getString("nick");
					String Lpoint = "";
					String dmod = "m ";
					idist = Integer.parseInt(jarray.getJSONObject(i).getString(
							"dist"));
					if (idist >= 1000) {
						idist = idist / 1000;
						dmod = "km ";
					}
					Lpoint = idist + dmod + nick;
					list.add(Lpoint);
				}
				return list;
			} catch (JSONException e) {
				Log.w("WARNING", e.getMessage());
				Toast
						.makeText(getBaseContext(),
								"Keine Piraten in deiner Umgebung!",
								Toast.LENGTH_SHORT).show();
			}
		} catch (ClientProtocolException e) {
			Toast.makeText(getBaseContext(),
					"Internet ist deaktiviert, oder nicht verf�gbar!",
					Toast.LENGTH_SHORT).show();

		} catch (IOException e) {
			Toast.makeText(getBaseContext(),
					"Internet ist deaktiviert, oder nicht verf�gbar!",
					Toast.LENGTH_SHORT).show();
			Log.w("ERROR", e.getMessage());
		}
		Log.w("ERROR", "is null");
		return null;
	}

	private class MyLocationlistener implements LocationListener {
		public void onLocationChanged(Location loc) {
			if (loc != null) {

			} else {
				Toast.makeText(getBaseContext(), "Long + Lat are null",
						Toast.LENGTH_SHORT).show();
			}
		}

		public void onProviderDisabled(String provider) {
			Toast.makeText(getBaseContext(), "GPS ist deaktiviert!",
					Toast.LENGTH_SHORT).show();
		}

		public void onProviderEnabled(String provider) {
			Toast.makeText(getBaseContext(), "GPS ist aktiviert!",
					Toast.LENGTH_SHORT).show();
			refresh();

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}
}
